﻿using System;
using System.Linq;
using System.Reflection;
using Ef.Core.Imp.Entity;
using Microsoft.EntityFrameworkCore;

namespace Ef.Core.Imp
{
    /// <summary>
    /// 自定义 数据上下文
    /// </summary>
    public class DynamicDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //写入连接字符串
            optionsBuilder.UseSqlServer("Data Source=.\\SQLSERVER;Initial Catalog=EfCore.Test;User ID=sa;Pwd=123");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var assembly = Assembly.GetExecutingAssembly();
            foreach (var type in assembly.ExportedTypes)
            {
                if (type.IsClass && type != typeof(EntityBase) && typeof(EntityBase).IsAssignableFrom((Type) type))
                {
                    var method = modelBuilder.GetType().GetMethods().FirstOrDefault(x => x.Name == "Entity");

                    if (method != null)
                    {
                        method = method.MakeGenericMethod(type);
                        method.Invoke(modelBuilder, null);
                    }
                }
            }
            base.OnModelCreating(modelBuilder);
        }
    }
}
